package com.lagou.service;

import com.lagou.pojo.DataBaseEntity;
import com.lagou.zkClient.ZkClientFactory;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;

/**
 * @author
 */
@Service
public class ZkConfigService {

    public static final String DATABASE_CONFIG = "/dataBaseConfig";

    private CuratorFramework zkClient = ZkClientFactory.getZkClient();

    public void updateDBConfig(DataBaseEntity dataBaseEntity) throws Exception {
        Field[] declaredFields = DataBaseEntity.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            String name = declaredField.getName();
            declaredField.setAccessible(true);
            if(declaredField.get(dataBaseEntity) != null){
                //如果没有配置，创建数据库配置，存在则更新
                if(zkClient.checkExists().forPath(DATABASE_CONFIG + "/" + name) == null){
                    zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT).forPath(DATABASE_CONFIG + "/" + name, declaredField.get(dataBaseEntity).toString().getBytes());
                } else {
                    zkClient.setData().forPath(DATABASE_CONFIG + "/" + name, declaredField.get(dataBaseEntity).toString().getBytes());
                }
            }
        }
    }
    
}
